import { injectable, inject } from 'inversify'
import { DB } from '../../db';
import { UserDto } from './user.dto'
import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator'
import { JWT } from '../../jwt'

/**
 * ## User 逻辑层
 */
@injectable()
export class UserServices {
  constructor(
    @inject(DB) private readonly DB: DB,
    @inject(JWT) private readonly JWT: JWT
  ) { }

  /** 登录逻辑 */
  public async login() {
    // 执行查询逻辑
    return await this.DB.prisma.user.findMany()
  }

  /** 注册逻辑 */
  public async signup(user: UserDto) {
    // 转换数据类型
    let userDto = plainToClass(UserDto, user)

    // 验证数据类型
    const errors = await validate(userDto)

    console.log(errors);

    if (errors.length) {
      return '数据类型错误'
    } else {
      const result = await this.DB.prisma.user.create({ data: user })
      return {
        ...result,
        token: this.JWT.createToken(result)
      }
    }
  }
}